//
//  WalletViewController.m
//  MyWallet
//
//  Created by 小肥羊 on 15/7/15.
//  Copyright (c) 2015年 小肥羊. All rights reserved.
//

#import "WalletViewController.h"

static NSString *WalletRecordCellWithIdentifier = @"WalletRecordCell";
@interface WalletViewController ()

@end

@implementation WalletViewController
#pragma mark - 惰性初始化
- (TotalAssets *)totalAssets
{
    if (!_totalAssets) {
        _totalAssets = [TotalAssets sharedManager];
        _totalAssets.delegate = self;
    }
    return _totalAssets;
}

- (UITableView *)walletRecordView
{
    if (!_walletRecordView) {
        _walletRecordView = [[UITableView alloc] initWithFrame:CGRectMake(50.0f, kNavbarHeight + 12, kScreenWidth - 100, kScreenHeight - kNavbarHeight - 24) style:UITableViewStylePlain];
        _walletRecordView.delegate = self;
        _walletRecordView.dataSource = self;
        [_walletRecordView registerNib:[UINib nibWithNibName:WalletRecordCellWithIdentifier bundle:nil] forCellReuseIdentifier:WalletRecordCellWithIdentifier];
    }
    return _walletRecordView;
}

- (PurseView *)purseView
{
    if (!_purseView) {
        _purseView = [[PurseView alloc] initWithFrame:CGRectMake(0, kNavbarHeight + 12, kScreenWidth - 80, kScreenHeight - kNavbarHeight - 24)];
        _purseView.delegate = self;
        UISwipeGestureRecognizer *recognizerRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(openPurseView:)];
        recognizerRight.direction = UISwipeGestureRecognizerDirectionRight;
        [_purseView addGestureRecognizer:recognizerRight];
        UISwipeGestureRecognizer *recognizerLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(closePurseView:)];
        recognizerLeft.direction = UISwipeGestureRecognizerDirectionLeft;
        [_purseView addGestureRecognizer:recognizerLeft];
    }
    return _purseView;
}

- (CardPackageView *)cardPackageView
{
    if (!_cardPackageView) {
        _cardPackageView = [[CardPackageView alloc] initWithFrame:CGRectMake(80.0f, kNavbarHeight + 12, kScreenWidth - 80, kScreenHeight - kNavbarHeight - 24)];
        _cardPackageView.delegate = self;
        UISwipeGestureRecognizer *recognizerRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(openCardPackageView:)];
        recognizerRight.direction = UISwipeGestureRecognizerDirectionRight;
        [_cardPackageView addGestureRecognizer:recognizerRight];
        UISwipeGestureRecognizer *recognizerLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(closeCardPackageView:)];
        recognizerLeft.direction = UISwipeGestureRecognizerDirectionLeft;
        [_cardPackageView addGestureRecognizer:recognizerLeft];
    }
    return _cardPackageView;
}

- (NSMutableArray *)walletRecord
{
    if (!_walletRecord) {
        _walletRecord = [[WalletLocalData sharedManager] recordArrayWithCount:100 MoneyFrom:nil];
        [self.walletRecordView reloadData];
    }
    return _walletRecord;
}

#pragma mark - 视图手势
- (void)openPurseView:(UISwipeGestureRecognizer *)tap
{
    [self showPurseView:YES];
    [self showCardPackageView:NO];
}

- (void)closePurseView:(UISwipeGestureRecognizer *)tap
{
    [self showPurseView:NO];
}

- (void)openCardPackageView:(UISwipeGestureRecognizer *)tap
{
    [self showCardPackageView:NO];
}

- (void)closeCardPackageView:(UISwipeGestureRecognizer *)tap
{
    [self showCardPackageView:YES];
    [self showPurseView:NO];
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [WalletLocalData sharedManager].delegate = self;
    [self creatUI];
}

- (void)creatUI
{
    UIBarButtonItem *backIetm = [[UIBarButtonItem alloc] init];
    backIetm.title =@"返回";
    [self.navigationItem setBackBarButtonItem:backIetm];
    
    [self.view addSubview:self.walletRecordView];
    [self.view addSubview:self.purseView];
    [self.view addSubview:self.cardPackageView];
    [self showPurseView:NO];
    [self showCardPackageView:NO];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.cardPackageView upCardPackage:self.totalAssets];
    [self.purseView setMoney:self.totalAssets.walletMoney];
    [self setTitle:[[NSString alloc] initWithFormat:@"$ %.2f",[self.totalAssets totalAssets]]];
    self.passDict = nil;
}

- (void)dealloc
{
    //移除代理
    self.totalAssets.delegate = nil;
    self.purseView.delegate = nil;
    self.cardPackageView.delegate = nil;
    [WalletLocalData sharedManager].delegate = nil;
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.walletRecord.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60.0f;
}

/*! @brief Cell单元格 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WalletRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:WalletRecordCellWithIdentifier];
    if (cell == nil) {
        NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:WalletRecordCellWithIdentifier owner:nil options:nil];
        cell = [nibs lastObject];
    }
    NSDictionary *dict = self.walletRecord[indexPath.row];
    NSDate *recordDtate = dict[@"RecordDtate"];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    [cell.moneyFrom setText:dict[@"MoneyFrom"]];
    [cell.moneyFor setText:dict[@"MoneyFor"]];
    [cell.remarks setText:dict[@"Remarks"]];
    [cell.recordDate setText:[dateformatter stringFromDate:recordDtate]];
    [cell moneyText:dict[@"Money"] Save:[dict[@"CheckoutType"] isEqualToString:@"1"]];
    return cell;
}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setEditing:NO animated:YES];
    NSDictionary *dict = self.walletRecord[indexPath.row];
    if ([[WalletLocalData sharedManager] deleteRecord:dict[@"RecordDtate"]]) {
        [[TotalAssets sharedManager] reduction:dict[@"MoneyFrom"] Money:[dict[@"Money"] floatValue] IsSave:[dict[@"CheckoutType"] isEqualToString:@"0"]];
        [self.cardPackageView upCardPackage:self.totalAssets];
        [self.purseView setMoney:self.totalAssets.walletMoney];
        [self.walletRecord removeObjectAtIndex:indexPath.row];
        [tableView beginUpdates];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [tableView endUpdates];
    }
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"还原";
}


#pragma mark - 操作
/*! @brief 是否显示钱袋 */
- (void)showPurseView:(BOOL)isShow
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:@"ShowPurse" context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5];
    CGRect rect = [self.purseView frame];
    if (isShow) {
        rect.origin.x = 0.0f;
    } else {
        rect.origin.x = 50.0f - rect.size.width;
    }
    [self.purseView setFrame:rect];
    [UIView commitAnimations];
}
/*! @brief 是否显示卡包 */
- (void)showCardPackageView:(BOOL)isShow
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:@"ShowCardPackage" context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5];
    CGRect rect = [self.cardPackageView frame];
    if (isShow) {
        rect.origin.x = kScreenWidth - rect.size.width;
    } else {
        rect.origin.x = kScreenWidth - 50.0f;
    }
    [self.cardPackageView setFrame:rect];
    [UIView commitAnimations];
}

#pragma mark - 钱袋代理
/*! @brief 存钱到钱袋 */
- (void)saveMoney:(PurseView *)purseView
{
    self.passDict = [[NSMutableDictionary alloc] initWithDictionary:@{@"PASSKEY_FUNCTION":@"SavePurse"}];
    [self performSegueWithIdentifier:@"SavePurse" sender:self];
}
/*! @brief 从钱袋取钱 */
- (void)drawMoney:(PurseView *)purseView
{
    self.passDict = [[NSMutableDictionary alloc] initWithDictionary:@{@"PASSKEY_FUNCTION":@"DrawPurse"}];
    [self performSegueWithIdentifier:@"DrawPurse" sender:self];
}
/*! @brief 查看钱包记录 */
- (void)checkCard:(PurseView *)purseView
{
    self.passDict = [[NSMutableDictionary alloc] initWithDictionary:@{@"PASSKEY_FUNCTION":@"QueryRecord"}];
    [self performSegueWithIdentifier:@"QueryRecord" sender:self];
}

#pragma mark - 卡包代理
/*! @brief 存钱到卡里 */
- (void)saveMoney:(CardPackageView *)cardPackageView CardView:(CardView *)cardView AtIndex:(NSInteger)index
{
    if (cardView.isActivation) {
        self.passDict = [[NSMutableDictionary alloc] initWithDictionary:@{@"PASSKEY_FUNCTION":@"SaveCard",@"cardIndex":[NSString stringWithFormat:@"%@", @(index)]}];
        [self performSegueWithIdentifier:@"SaveCard" sender:self];
    }
}
/*! @brief 从卡里取钱 */
- (void)drawMoney:(CardPackageView *)cardPackageView CardView:(CardView *)cardView AtIndex:(NSInteger)index
{
    if (cardView.isActivation) {
        self.passDict = [[NSMutableDictionary alloc] initWithDictionary:@{@"PASSKEY_FUNCTION":@"DrawCard",@"cardIndex":[NSString stringWithFormat:@"%@", @(index)]}];
        [self performSegueWithIdentifier:@"DrawCard" sender:self];
    }
}
/*! @brief 查看卡信息 */
- (void)checkCard:(CardPackageView *)cardPackageView CardView:(CardView *)cardView AtIndex:(NSInteger)index
{
    if (cardView.isActivation) {
        self.passDict = [[NSMutableDictionary alloc] initWithDictionary:@{@"PASSKEY_FUNCTION":@"DrawCard",@"cardIndex":[NSString stringWithFormat:@"%@", @(index)]}];
        [self performSegueWithIdentifier:@"QueryRecord" sender:self];
    }
}
/*! @brief 激活一张卡 */
- (void)activationCard:(CardPackageView *)cardPackageView CardView:(CardView *)cardView AtIndex:(NSInteger)index
{
    self.passDict = [[NSMutableDictionary alloc] initWithDictionary:@{@"PASSKEY_FUNCTION":@"ActivationCard",@"cardIndex":[NSString stringWithFormat:@"%@", @(index)]}];
    [self performSegueWithIdentifier:@"ActivationCard" sender:self];
}
/*! @brief 注销卡 */
- (void)cancellationCard:(CardPackageView *)cardPackageView CardView:(CardView *)cardView AtIndex:(NSInteger)index
{
    self.passDict = [[NSMutableDictionary alloc] initWithDictionary:@{@"PASSKEY_FUNCTION":@"CancellationCard",@"cardIndex":[NSString stringWithFormat:@"%@", @(index)]}];
    [self performSegueWithIdentifier:@"CancellationCard" sender:self];
}

#pragma mark - 总资产代理
- (void)upTotalAssets:(TotalAssets *)totalAssets Money:(float)money
{
    [self setTitle:[[NSString alloc] initWithFormat:@"$ %.2f",money]];
}

#pragma mark - 数据库代理
- (void)upWalletLocalData:(WalletLocalData *)localData Message:(NSString *)message
{
    self.walletRecord = [[WalletLocalData sharedManager] recordArrayWithCount:100 MoneyFrom:nil];
    [self.walletRecordView reloadData];
}

#pragma mark - 传参
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    WalletBaseViewController *send = segue.destinationViewController;
    send.receiveDict = self.passDict;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
